#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
@author: yuejl
@application:
@contact: lewyuejian@163.com
@file: logconfig.py
@time: 2021/10/17 0017 12:59
@desc:
'''
import configparser
from configparser import NoOptionError, NoSectionError
import os
import logging
import codecs

from integratior_service.controllers.common.public import Public
from integratior_service.controllers.common.exceptions import SeleniumTypeError

from integratior_service import BASE_PATH

# PROJECT_DIR = os.path.dirname(
#     os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
# )

CONFIG_PATH = os.path.join(BASE_PATH, 'conf', 'config.ini')


class GetConfig(object):
    @staticmethod
    def get_config() -> configparser.ConfigParser:
        config = configparser.ConfigParser()
        with open(
            file=CONFIG_PATH, mode="rb"
        ) as f:  # 2018-6-10 BEGIN 判断文件的编码类型 如果是UTF-8 BOM格式，则将其转化为无BOM格式
            s = f.read()
        if s.startswith(codecs.BOM_UTF8):  # 带BOM的文件是以 b'\xef\xbb\xbf' 开头
            s = s[len(codecs.BOM_UTF8):]  # 截取 b'\xef\xbb\xbf' 到文件结尾
            with open(file=CONFIG_PATH, mode="wb") as f:  # 保存为无BOM格式
                f.write(s)
        coding = Public.get_file_coding(filepath=CONFIG_PATH).get("encoding")
        config.read(
            filenames=CONFIG_PATH, encoding=coding
        )  # 2018-6-10 END 判断文件的编码类型 如果是UTF-8 BOM格式，则将其转化为无BOM格式
        return config

    @property
    def project_dir(self) -> str:
        # return self.get_config().get(section="PROJECT", option="project_dir")
        # 不在需要配置项目路径，项目迁移更加灵活。

        return BASE_PATH

    @property
    def logging_level(self) -> int:
        section = "LOG"
        option = "logging_level"
        default = "INFO"
        try:
            level = self.get_config().get(section=section, option=option)
        except (NoOptionError, NoSectionError):
            level = default
        if str.upper(level) == "DEBUG":
            return logging.DEBUG
        elif str.upper(level) == "INFO":
            return logging.INFO
        elif str.upper(level) == "WARN" or str.upper(level) == "WARNING":
            return logging.WARNING
        elif str.upper(level) == "CRITICAL" or str.upper(level) == "FATAL":
            return logging.CRITICAL
        elif str.upper(level) == "ERROR":
            return logging.ERROR
        else:
            raise SeleniumTypeError(
                '配置文件中定义的日志级别logging_level为"%s",请填写以下几种级别“INFO、DEBUG、WARNING、ERROR、CRITICAL”'
                % level
            )


# 2020-4-2 zz: 为了能够实时获取config.ini文件内容，将Config类改为Config对象(GetConfig的实例)
Config = GetConfig()
# class Config(object):
#     # 项目路径
#     project_dir = GetConfig().project_dir
#     # 配置输出日志级别
#     logging_level = GetConfig().logging_level